
const Group = require('./models.js')
const Util = require('../utils/util.js')

module.exports = {
  /**
   * 创建一个组织类型，创建需要最高权限，超级管理员只允许一个存在
   * @param {*} req 
   * @param {*} res 
   * @param {*} next 
   */
    async createGroup(req, res, next) {
        // 校验传入的参数
        let fields = req.body;
        // try {
        //   // let validateResult = checkCreateUserFields(fields, req)
        //   // if (!validateResult) {
        //   //   return res.status(500).send(Util.renderApiErr(req, res, 500, '数据校验失败'))
        //   // }
        // } catch (err) {
        //   return res.status(500).send(Util.renderApiErr(req, res, 500, err))
        // }

        const obj = {
          groupname: fields.groupname,
          groupcode: fields.groupcode || '',
          groupphone: fields.groupphone || '',
          groupuser: fields.groupuser || '',
          description: fields.description || '',
          grouptype: fields.grouptype || '',
          roles: fields.roles || [],
          enable: fields.enable ? true : false
        }

        const newGroup = new Group(obj)

        try {
          let _groupCode = await Group.findOne({ groupcode: obj.groupcode }, {grouptype: obj.grouptype})
          if (_groupCode) {
            return res.status(500).send(Util.renderApiErr(req, res, 500, '组织编码已被占用'))
          }

          let cateObj = await newGroup.save()
          // 更新sortPath defaultUrl
          return res.send(Util.renderApiData(req, res, 200, '组织新增成功', { id: cateObj._id }))
        } catch (err) {
          return res.status(500).send(Util.renderApiErr(req, res, 500, err))
        }

    },

    /**
   * 获取组织类型列表
   * @param {*} req 
   * @param {*} res 
   * @param {*} next 
   */
    async getGroupList(req, res, next) {
        try {
          // log(req.query)
          let fields = req.query
          let page = Number(fields.page) || 1;
          let pageSize = Number(fields.pageSize) || 10;
          let queryObj = {}, sortObj = { create_time: -1 };
          let ref = fields.ref
          let grouptype = fields.grouptype

          if (grouptype) {
            queryObj.grouptype = grouptype
          }

          // // 排序
          // if (sortBy) {
          //   delete sortObj.create_time
          //   sortObj[sortBy] = -1
          // }

          // 查询文档
          // ref 关联表查询
          // ref:{
          //   path:'grouptype',
          //   select:'_id name typecode parent_id'
          // }
          if(ref === 'all'){
            ref = [
              {
                path:'grouptype',
                select:'_id name typecode parent_id'
              },
              {
                path:'role',
                select:'_id rolename rolecode menu group'
              }
            ]
          }
          const groupList = await Group.find(queryObj).sort(sortObj).skip((page - 1) * pageSize).limit(pageSize).populate(ref).exec()
          const totalCounts = await Group.count(queryObj)

          // log(groupList)

          let GroupObj = {
            list: groupList,
            page: page,
            lastPage: Math.ceil(totalCounts / pageSize),
            pageSize: pageSize,
            totalCounts: totalCounts
          }
          return res.send(Util.renderApiData(req, res, 200, '组织列表获取成功', GroupObj))
        } catch (err) {
          return res.status(500).send(Util.renderApiErr(req, res, 500, err))
        }
    },
}